<?php
    /**
     * GiftAction
     * 礼物控制层
     *
     * @uses 
     * @package 
     * @version 
     * @copyright 2009-2011 SamPeng
     * @author SamPeng <sampeng87@gmail.com>
     * @license PHP Version 5.2 {@link www.sampeng.cn}
     */
class IndexAction extends Action{
	    private $icopath="";
	    private $private = null;
	    public function _initialize(){
	    	        //参数转义
                new_addslashes($_POST);
                new_addslashes($_GET);
	        $this->icopath = "../Public/images/ico/";
	        $this->assign('icopath',$this->icopath);
	    }
	    
	    public function index(){
	   	   $friend = $this->api->friend_get();
	   	   if(!empty($friend)) $this->private = "uid in (".implode(',',$friend).")";
	   	   $this->__setAssign($friend);
	       $this->display();
	    }
	    
	    public function my(){
	    	$this->private = "uid = {$this->mid}";
            $this->__setAssign($this->mid);
            $this->display();
	    }
	    public function all(){
	    	$this->private = "private = 0";
	    	$this->__setAssign(null,0);
	    	$this->display();
	    }
	    
	    public function addPosterSort(){
	    	$posterTypeDao = D('PosterType');
	    	$posterType = $posterTypeDao->getType();
	    	$this->assign('posterType',$posterType);
	    	$this->display();
	    }
	    public function personal(){
	    	$are_friends = $this->api->friend_areFriends($this->mid,$this->uid);
	    	if($are_friends){
	    		$this->private = "uid = {$this->uid}";
	    		$this->__setAssign($this->uid);
	    	}else{
	    		$this->private = "uid = {$this->uid} AND private = 0";
	    		$this->__setAssign($this->uid,0);
	    	}
	    	$this->assign('uid',$this->uid);
	    	$this->assign('name',getUserName($this->uid));
            $this->display();
	    }
	    public function posterDetail(){
	    	$posterTypeDao = D('PosterType');
	    	$poster = D('Poster');
	    	$id = intval($_GET['id']);
	    	
	    	if($id == 0){
	    		$this->error("错误的信息地址.请检查后再访问");
                exit;
	    	}
	    	
	    	$posterData     = $poster->getPoster($id,$this->mid);
	        if(!$posterData){
                $this->error("这个信息被删除或者不允许查看");
                exit;
            }
            
	    	$posterType = $posterTypeDao->getType($posterData['pid']);

	    	$posterTypeExtraField = $posterTypeDao->getExtraField($posterType['extraField']);
	    	unset($posterType['extraField']);
	    	
	    	if($posterData['uid'] == $this->mid){
	    		$this->assign('admin',1);
	    	}
	    	
	    	$this->assign('poster',$posterData);
	    	$this->assign('extraField',$posterTypeExtraField);
	    	$this->assign('type',$posterType);
	    	$this->display();
	    }
	    
	    public function doDeletePoster(){
	    	$id = intval($_POST['id']);
	    	if(0 == $id){
	    		echo -3;
	    	}else{
	    		$poster = D('Poster');
	    		echo $poster->deletePoster($id,$this->mid);
	    	}
	    }
	    private function __setAssign($uid = null,$private = null){
	       $poster = D('Poster');
	       $pid = intval($_GET['pid'])?intval($_GET['pid']):null;
	       $stid = intval($_GET['stid'])?intval($_GET['stid']):null;
           $posterData = $poster->getPosterList($pid,$stid,$uid,$private);
           $this->getPosterType ($poster);
           $this->assign($posterData);
	    }

        private function getPosterType($poster){
            $posterTypeDao = D('PosterType');
            $posterSmallTypeDao = D('PosterSmallType');
	        $posterType = $posterTypeDao->getType();
	        foreach($posterType as $value){
	   	       $id = $value['id'];
	           if(isset($value['type']) && $id == intval($_GET['pid'])){
	        	  $posterSmallType = $posterSmallTypeDao->getPosterSmallType($value['type']);
	           }
	       }

           $posterSmallType = $this->getPosterCount($poster,$posterSmallType);
	       $this->assign('posterType',$posterType);
	       $this->assign('type',$posterSmallType);
        }
        
        private function getPosterCount($poster,$posterSmallType){
            $tableName = $poster->getTableName();
            $otherWhere = $this->private;
            if(!empty($posterSmallType)){
                for($i=0;$i<count($posterSmallType);$i++){
                	if(isset($otherWhere)){
                		$where = "type = {$posterSmallType[$i]['id']} AND ".$otherWhere;
                	}else{
                		$where = "type = {$posterSmallType[$i]['id']}";
                	}
                    $sql[] = "select '{$posterSmallType[$i]['id']}' as `id`,count(1) as count from  {$tableName} where {$where}";
                }
            }
            $sql = implode( ' union all ',$sql );
            $count = $poster->query($sql);
            $temp_array = array();
            foreach($count as $value){
            	$temp_array[$value['id']] = $value['count'];
            }
            $result = $posterSmallType;
            foreach ($result as &$value){
            	$value['count'] = $temp_array[$value['id']] ;
            }
            return $result;
        }

	   
	   public function addPoster(){
	       $posterTypeDao = D('PosterType');
	       $poster = $posterTypeDao->getType(intval($_GET['typeId']));
	       $posterSmallTypeDao = D('PosterSmallType');
	       $userInfo          = $this->api->UserInfo_get($this->mid,'info');
	       $userInfo['area'] = getAreaInfo($userInfo['居住地区']);
	       $userInfo['ts_areaval'] = $userInfo['居住地区'];
	       $posterSmallType = $posterSmallTypeDao->getPosterSmallType($poster['type']);
	       $this->assign('smileList',$this->getSmile($this->opts['ico_type']));
           $this->assign('smilePath',$this->getSmilePath($this->opts['ico_type']));
           $this->assign('smallType',$posterSmallType);
           $this->assign('userInfo',$userInfo);
	       $this->assign($poster);
	       $this->display();
	   }
	   
	   public function editPoster(){
           $posterDao = D('Poster');	   	
	   	   $posterData     = $posterDao->getPoster($_GET['id'],$this->mid);
	   	   
	   	   $posterTypeDao = D('PosterType');
           $poster = $posterTypeDao->getType(intval($_GET['typeId']));
           $posterSmallTypeDao = D('PosterSmallType');
           $userInfo['area'] = getAreaInfo($posterData['address_province'].','.$posterData['address_city']);
           $userInfo['ts_areaval'] = $posterData['address_province'].','.$posterData['address_city'];
           $posterData['deadline'] = date("Y-m-d H:i:s",$posterData['deadline']);
           $posterSmallType = $posterSmallTypeDao->getPosterSmallType($poster['type']);
           $this->assign('smileList',$this->getSmile($this->opts['ico_type']));
           $this->assign('smilePath',$this->getSmilePath($this->opts['ico_type']));
           $this->assign('smallType',$posterSmallType);
           $this->assign('userInfo',$userInfo);
           $this->assign('poster',$posterData);
           $this->assign($poster);
           $this->display();
	   }
	   
	   public function doEditPoster(){
            $dao = D('Poster');
            $condition['id']=intval($_POST['id']);	   
            	   
		    $map['title']      = t($_POST['title']);
	        $map['type']       = $_POST['type'];
	        $map['content']    = $_POST['explain'];
	        $map['contact']    = t($_POST['contact']);
	        $map['deadline'] = $deadline = $this->_paramDate( $_POST['deadline'] );
	        
	        $address = explode(',',$_POST['ts_areaval']);
	        $map['address_province'] = $address[0];
	        $map['address_city'] = $address[1];
	        $sendPosterTime =$dao->where('id='.intval($_POST['id']))->getField('cTime'); 
	        if( $deadline <  $sendPosterTime) {
	            $this->error( "结束时间不得小于发布时间" );
	            exit;
	        }
	        $map = $this->_extraField($map,$_POST);
	        //得到上传的图片
	        $option = array();
	        $option['save_photo']['albumId'] = intval( $_POST['albumId'] );
	        $cover = $this->api->attach_upload( 'poster_cover',$option );
	        $cover['status'] && $map['conver'] = $cover['info'][0]['savepath'].$cover['info'][0]['savename'];
	        
	        $map['private'] = isset($_POST['friend'])?$_POST['friend']:0;

	        $rs = $dao->where($condition)->save($map);
	        if($rs){
	        	$jumpUrl = __URL__."/posterDetail/id/".intval($_POST['id']);
	        	$this->assign('jumpUrl',$jumpUrl);
	        	$this->success("编辑成功");
	        	exit;
	        }else{
	        	$this->error('编辑失败');
	        }
	   }
	   
	    private function _paramDate( $date ) {
	        $date_list = explode( ' ',$date );
	        list( $year,$month,$day ) = explode( '-',$date_list[0] );
	        list( $hour,$minute,$second ) = explode( ':',$date_list[1] );
	        return mktime( $hour,$minute,$second,$month,$day,$year );
	    }
	   public function doAddPoster(){
	   	$map['title']      = t($_POST['title']);
        $map['type']       = $_POST['type'];
        $map['pid']        = $_POST['pid'];
        $map['content']    = $_POST['explain'];
        $map['contact']    = t($_POST['contact']);
        $map['deadline'] = $deadline = $this->_paramDate( $_POST['deadline'] );
        $map['uid']      = $this->mid;
        $map['name']     = $this->my_name;
        $map['cTime']    = time();
        
        $address = explode(',',$_POST['ts_areaval']);
        $map['address_province'] = $address[0];
        $map['address_city'] = $address[1];

        if( $deadline < time() ) {
            $this->error( "结束时间不得小于当前时间" );
            exit;
        }
        $map = $this->_extraField($map,$_POST);
        //得到上传的图片
        $option = array();
        $option['save_photo']['albumId'] = intval( $_POST['albumId'] );
        $cover = $this->api->attach_upload( 'poster_cover',$option );
        $map['conver'] = $cover['status']?$cover['info'][0]['savepath'].$cover['info'][0]['savename']:null;
        $map['private'] = isset($_POST['friend'])?$_POST['friend']:0;
        $dao = D('Poster');
        $rs = $dao->add($map);
        if($rs){
            $count = $dao->where( 'uid ='.$map['uid'] )->count();
            $this->api->space_changeCount( 'poster',$count );
            
            isset($_POST['feed']) && $this->doFeed($map,$rs);
            $jumpUrl = __URL__."/posterDetail/id/".$rs;
            $this->assign('jumpUrl',$jumpUrl);
            $this->success("发布成功,即将跳转到内容页");
        }
	   }
	   
	   private function doFeed($data,$id){
	   	   $posterTypeDao = D('PosterType');
	       $title['posterType'] = $posterTypeDao->getTypeName($data['pid']);
	       $url = sprintf("%s/Index/posterDetail/id/%s",'{SITE_URL}',$id);
	       $title['title'] = sprintf("<a href='%s'>%s</a>",$url,$data['title']);
	       $body['comment'] = getBlogShort($data['content'],40);
	       $this->api->feed_publish('poster',$title,$body,$this->appId);
	   }
	   
	   private function _extraField($map,$post){
	   	for($i=1;$i<6;$i++){
	   		if(isset($post['extra'.$i]) && !empty($post['extra'.$i])){
	   			if(is_array($post['extra'.$i])){
	   				$map['extra'.$i] =implode(',',$post['extra'.$i]);
	   			}else{
                    $map['extra'.$i] = $post['extra'.$i];	   				
	   			}

	   		}
	   	}
	   	return $map;
	   }
            /**
         * TODO 删除
         */
        public function commentSuccess() {
        //$post = str_replace('\\', '', stripslashes($_POST['data']));
                $result = json_decode(stripslashes($_POST['data']));  //json被反解析成了stdClass类型
                //$count = $this->__setBlogCount($result->appid);
                //发送两条消息
                $data = $this->__getNotifyData($result);
                $rs = $this->api->comment_notify('poster',$data,$this->appId);
                echo $rs;
        }
        
        /**
         * TODO 删除
         */
        private function __getNotifyData($data) {
                //发送两条消息
                $poster = D('Poster');
                $result['toUid'] = $data->toUid;
                $need  = $poster->where('id='.$data->appid)->field('uid,title')->find();
                $result['uids'] =$need['uid'];
                $result['url'] = sprintf('%s/Index/posterDetail/id/%s','{'.$this->appId.'}',$data->appid);
                $result['title_body']['comment'] = $data->comment;
                $result['title_data']['title'] = sprintf("<a href='%s'>%s</a>",$result['url'],$need['title']);
                $result['title_data']['type']  = "招贴板";
                		       $result['title_body']['id'] = $data->id;
                $result['title_body']['toId'] = $data->toId?$data->toId:$data->id;
                $result['title_body']['appid'] = $data->appid;
                $result['title_body']['quietly'] = $data->quietly;
                $result['title_body']['ctype']  = $data->type;
                $result['title_data']['uids'] = $need['uid'];
                $result['title_data']['table'] = $poster->getTableName();
                $result['title_data']['ctype'] = $data->type;
                $result['title_data']['appid'] = $this->appId;
                $result['title_data']['name']  = getUserName($result['uids']);
                return $result;
        }
}
